/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package towerz.system;

import java.io.IOException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import towerz.game.Score;

/**
 *
 * @author TimotiusNC
 */
public class HighScoreReaderWriter {

    public static void addRecordToRms(Score oneScore, String rsName) {
        Score[] tempOneScores = null;
        Score[] otherTempOneScores = null;
        RecordStore rs = null;
        byte[] data = null;

        tempOneScores = readOneScoreRecords(rsName);

        if(tempOneScores != null) {
            try {
                RecordStore.deleteRecordStore(rsName);
            } catch (RecordStoreException ex) {}

            otherTempOneScores = new Score[tempOneScores.length+1];
            for(int i=0; i<tempOneScores.length; i++) {
                otherTempOneScores[i] = new Score(tempOneScores[i].getUsername(), tempOneScores[i].getScore());
            }
            otherTempOneScores[tempOneScores.length] = new Score(oneScore.getUsername(), oneScore.getScore());
            Score.sortOneScoreArray(otherTempOneScores);
        }

        try {
            rs = RecordStore.openRecordStore(rsName, true);

            if(otherTempOneScores != null) {
                int recordsToBeInserted = otherTempOneScores.length < 5 ? otherTempOneScores.length : 5;
                for(int i=0; i<recordsToBeInserted; i++) {
                    data = otherTempOneScores[i].toByteArray();
                    rs.addRecord(data, 0, data.length);
                }
            }
            else {
                data = oneScore.toByteArray();
                rs.addRecord(data, 0, data.length);
            }

            rs.closeRecordStore();
        }
		catch (RecordStoreException ex) {}
		catch (IOException ex) {}
    }

    public static Score[] readOneScoreRecords(String rsName) {
        Score[] retval = null;
        RecordStore rs = null;
        byte[] data = null;
        
        try {
            rs = RecordStore.openRecordStore(rsName, true);

            if(rs.getNumRecords() != 0) {
                retval = new Score[rs.getNumRecords()];
                int nextID = rs.getNextRecordID();

                for(int id=1; id<nextID; id++) {
                    int size = rs.getRecordSize(id);
                    if (data == null || data.length < size) {
                        data = new byte[size];
                    }

                    rs.getRecord(id, data, 0);
                    retval[id-1] = new Score("dummy", -1);
                    retval[id-1].fromByteArray(data);
                }
            }

            rs.closeRecordStore();
        }
		catch (RecordStoreException ex) {}
		catch (IOException ex) {}

        return retval;
    }
}
